'use strict';
const os = require('os');
const utils = {
    ERROR: {
        code: -1,
        status: "fail",
        msg: 'fail',
    },
    SUCCESS: {
        code: 200,
        status: "success",
        msg: 'success',
    },
    unique(arr) {
        return arr.filter(function (item, index, arr) {
            return arr.indexOf(item) === index;
        });
    },
    //获取本机ip地址
    getIPAdress() {
        var interfaces = os.networkInterfaces();
        for (var devName in interfaces) {
            var iface = interfaces[devName];
            for (var i = 0; i < iface.length; i++) {
                var alias = iface[i];
                if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
                    return alias.address;
                }
            }
        }
    },
    //token转userId
    tokenByUserId(ctx) {
        const token = ctx.headers.authorization ? ctx.headers.authorization : '';
        return ctx.app.jwt.verify(token.substring(7), ctx.app.config.jwt.secret).data.userId //解析token
    },
    /**
     * 初始化数据库表
     * @param modelVm  数据库模型实列
     * @param data Array 数据数组
     * @returns {Promise<void>}
     */
    async initModel(modelVm, data = []) {
        const res = await modelVm.findOne({
            where: data[0],
        })
        if (!res) modelVm.bulkCreate(data)
        return res
    },
    //时间戳转换方法    date:时间戳数字 转 2013-01-01 //00:00:00
    formatDate(date, isNoSeconds) {
        var date = new Date(date);
        var YY = date.getFullYear() + "-";
        var MM = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
        var DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
        // var hh = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
        // var mm = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
        // var ss = "";
        // if (!isNoSeconds) ss = ":" + (date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds());
        // else ss = "";
        return YY + MM + DD
    },
    // 深度克隆
    deepClone(obj) {
        // 判断arr是否为一个数组，返回一个bool值
        function isArray(arr) {
            return Object.prototype.toString.call(arr) === "[object Array]";
        }

        // 对常见的“非”值，直接返回原来值
        if ([null, undefined, NaN, false].includes(obj)) return obj;
        if (typeof obj !== "object" && typeof obj !== "function") {
            //原始类型直接返回
            return obj;
        }
        var o = isArray(obj) ? [] : {};
        for (let i in obj) {
            if (obj.hasOwnProperty(i)) {
                o[i] = typeof obj[i] === "object" ? utils.deepClone(obj[i]) : obj[i];
            }
        }
        return o;
    },
    // 获取距今n天前的日期
    getNDay(day) {
        var today = new Date();
        var beforMilliseconds = today.getTime() - 1000 * 3600 * 24 * day;
        var beforday = new Date();
        beforday.setTime(beforMilliseconds);
        var strYear = beforday.getFullYear();
        var strDay = beforday.getDate();
        var strMonth = beforday.getMonth() + 1;
        if (strMonth < 10) {
            strMonth = "0" + strMonth;
        }
        if (strDay < 10) {
            strDay = "0" + strDay;
        }
        var strYesterday = strYear + "-" + strMonth + "-" + strDay;
        return strYesterday
    },
    //获取上周起始时间结束时间、下周起始时间结束时间开始时间和本周起始时间结束时间;（西方）
    /***参数都是以周一为基准的***/
//上周的开始时间
// console.log(getWeekTime(7));
//上周的结束时间
// console.log(getWeekTime(1));
//本周的开始时间
// console.log(getWeekTime(0));
//本周的结束时间
// console.log(getWeekTime(-6));
//下周的开始时间
// console.log(getWeekTime(-7));
//下周结束时间
// console.log(getWeekTime(-13));
    getWeekTime(n) {
        var now = new Date();
        var year = now.getFullYear();
        //因为月份是从0开始的,所以获取这个月的月份数要加1才行
        var month = now.getMonth() + 1;
        var date = now.getDate();
        var day = now.getDay();
        console.log(date);
        //判断是否为周日,如果不是的话,就让今天的day-1(例如星期二就是2-1)
        if (day !== 0) {
            n = n + (day - 1);
        } else {
            n = n + day;
        }
        if (day) {
            //这个判断是为了解决跨年的问题
            if (month > 1) {
                month = month;
            }
            //这个判断是为了解决跨年的问题,月份是从0开始的
            else {
                year = year - 1;
                month = 12;
            }
        }
        now.setDate(now.getDate() - n);
        year = now.getFullYear();
        month = now.getMonth() + 1;
        date = now.getDate();
        // console.log(n);
        var s = year + "-" + (month < 10 ? ('0' + month) : month) + "-" + (date < 10 ? ('0' + date) : date);
        return s;
    }


};

module.exports = utils
